package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天客户端*/
public class Client {
    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    private Socket socket;
    public Client() {

        /**
         * localhost表示本机ip*/
        //初始化客户端
        try {
            System.out.println("正在连接服务端");
            socket=new Socket("localhost",8959);
            System.out.println("与服务器连接成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        //启动客服端
        //低级流，作用：将写出的字节流发生给链接的服务端
        try {
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);//转换流
            BufferedWriter bw = new BufferedWriter(osw);//缓冲字符流
            PrintWriter pw = new PrintWriter(bw,true);//自动行刷新


            Scanner scanner = new Scanner(System.in);
            while (true){
                System.out.println("请输入文字");
                String next = scanner.next();
                if ("exit".equals(next)){
                    break;
                }
                pw.println("客服端说："+next);
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                socket.close();//关闭流与服务的连接
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

}
